//
//  SettingViewController.m
//  ZPIOSEducation
//
//  Created by 董伟1 on 17/3/6.
//  Copyright © 2017年 mini1. All rights reserved.
//

#import "SettingViewController.h"
#import "SettingCell.h"
#import "ZPChangePwdViewController.h"
#import "ZPRegisterLoginViewController.h"
#import "ZPBaseNavigationController.h"

#define ClearCacheActionSheetTag  1000
#define LogOutActionSheetTag      1001

@interface SettingViewController () <UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate>
{
    UIView  *headerView;
    UIView  *footerView;
    NSMutableArray  *dataArray;
    UIView  *clearView;
}
@property (weak, nonatomic) IBOutlet UITableView *mainTableView;

@end

@implementation SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = @"设置";
    NSInteger cacheSize = [[SDImageCache sharedImageCache] getSize];
    NSString  *cacheStr = [NSString  stringWithFormat:@"%.2fMB",cacheSize/1024.0/1024.0];
    
    NSString  *versionStr = [NSString  stringWithFormat:@"v%@",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]];
    dataArray = [[NSMutableArray  alloc] initWithObjects:
                  [NSDictionary  dictionaryWithObjectsAndKeys:@"清除本地缓存",@"title",cacheStr,@"detail", nil],
                  [NSDictionary  dictionaryWithObjectsAndKeys:@"修改密码",@"title",@"",@"detail", nil],
                  [NSDictionary  dictionaryWithObjectsAndKeys:@"版本号",@"title",versionStr,@"detail", nil],
                   nil];
    
    self.mainTableView.tableHeaderView = [self  createTableHeaderView];
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self  checkLogIn];
}

- (void)checkLogIn
{
    if ([[ZPAuthStore  sharedZPAuthStore] isLogin]) {
        self.mainTableView.tableFooterView = [self  createTableFooterView];
        UIImageView  *headerImv = (UIImageView  *)[headerView  viewWithTag:1000];
        NSURL  *url = [NSURL  URLWithString:[NSString  stringWithFormat:@"%@",[[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"headUrl"]]];
        [headerImv  sd_setImageWithURL:url placeholderImage:[UIImage  imageNamed:@"headportrait"]];
        
        UILabel  *nameLab = (UILabel  *)[headerView  viewWithTag:1001];
        nameLab.text = [NSString  stringWithFormat:@"%@",[[ZPAuthStore  sharedZPAuthStore].userToDic objectForKey:@"userName"]];
        
    }else {
        self.mainTableView.tableFooterView = nil;
    }
}

- (UIView  *)createTableHeaderView
{
    if (headerView) {
        
    }else {
        headerView = [[[NSBundle mainBundle] loadNibNamed:@"SettingHeaderView" owner:self options:nil] lastObject];
        headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 140);
        
        UIImageView  *headerImv = (UIImageView  *)[headerView  viewWithTag:1000];
        headerImv.contentMode = UIViewContentModeScaleAspectFill;
        headerImv.clipsToBounds = YES;
        headerImv.layer.cornerRadius = 30.;
        headerImv.layer.masksToBounds = YES;
        
        UILabel  *nameLab = (UILabel  *)[headerView  viewWithTag:1001];
        nameLab.text = @"";
    }
    
    return headerView;
}

- (UIView  *)createTableFooterView
{
    if (footerView) {
        
    }else {
        footerView = [[[NSBundle mainBundle] loadNibNamed:@"SettingFooterView" owner:self options:nil] lastObject];
        footerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 60);
    }
    
    UIButton  *logoutBtn = (UIButton  *)[footerView  viewWithTag:2000];
    [logoutBtn  addTarget:self action:@selector(logOutButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    return footerView;
}

- (void)logOutButtonClick:(id)sender
{
    UIActionSheet  *actionSheet = [[UIActionSheet  alloc] initWithTitle:@"确认要退出登录吗?" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"退出" otherButtonTitles: nil];
    actionSheet.tag = LogOutActionSheetTag;
    [actionSheet  showInView:self.view];
}

- (void)doLogOutAction
{
    [[ZPAuthStore sharedZPAuthStore] clear];
    [[ZPNetworking  sharedZPNetworking] GET:APILoginOut parameters:nil progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"logOutNotification" object:nil];
    
    ZPBaseNavigationController *registerLoginNvc = [[ZPBaseNavigationController alloc] initWithRootViewController:[[ZPRegisterLoginViewController alloc] init]];
    self.view.window.rootViewController = registerLoginNvc;
    
}

- (void)cleanCache
{
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:nil]; // 更新前清除缓存方法 clearDisk
    [self.mainTableView reloadData]; // 刷新数据
    [self showClearView];  // 展示缓存已清除
    [self performSelector:@selector(hiddenClearView) withObject:nil afterDelay:1.]; // 单线程方法,只有当前调用此方法的函数执行完毕后，selector方法才会被调用
}

#pragma mark - ClearView
#pragma mark 显示
- (void)showClearView
{
    if (!clearView) {
        clearView = [[UIView  alloc] initWithFrame:CGRectMake((WIDTH(self.mainTableView) - 100) / 2, (HEIGHT(self.mainTableView) - 66) / 2, 100, 66)];
        clearView.backgroundColor = zFreeColor(0, 0, 0, 0.65);
        ViewRadius(clearView, 8.);
        [self.mainTableView  addSubview:clearView];
        
        
        UIImageView  *imageView = [[UIImageView  alloc] initWithFrame:CGRectMake(40, 12, 20, 20)];
        imageView.image = [UIImage  imageNamed:@"setting_clear"];
        [clearView  addSubview:imageView];
        
        UILabel  *label = [[UILabel  alloc] initWithFrame:CGRectMake(10, 38, 80, 20)];
        [[ZPShareView sharedSingleView] setupLabel:label masksToBounds:NO cornerRadius:0 backgroundColor:clear_color text:@"清除成功" textColor:white_color font:14. textAlignment:NSTextAlignmentCenter];
        [clearView  addSubview:label];
        NSDictionary  *tempDic = [NSDictionary  dictionaryWithObjectsAndKeys:@"清除本地缓存",@"title",@"0.00MB",@"detail", nil];
        [dataArray  replaceObjectAtIndex:0 withObject:tempDic];
        [self.mainTableView reloadData];
        
    }
    clearView.hidden = NO;
}

#pragma mark 隐藏
- (void)hiddenClearView
{
    if (clearView) {
        clearView.hidden = YES;
    }
}

#pragma mark - UITableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dataArray  count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44.;
}

- (UITableViewCell  *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"SettingCell";
    SettingCell  *cell = (SettingCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"SettingCell" owner:self options:nil] lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    NSInteger  row = [indexPath  row];
    NSDictionary  *tempDic = [dataArray  objectAtIndex:row];
    cell.titleLab.text = [NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"title"]];
    cell.detailLab.text = [NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"detail"]];
    cell.arrowImv.hidden = NO;
    if (row == 2) {
        cell.arrowImv.hidden = YES;
    }
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger  row = [indexPath  row];
    if (row == 0) {
        //清除本地缓存
        UIActionSheet  *actionSheet = [[UIActionSheet  alloc] initWithTitle:@"清除后，图片等信息需重新下载，确认清除?" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"清除" otherButtonTitles: nil];
        actionSheet.tag = ClearCacheActionSheetTag;
        [actionSheet  showInView:self.view];
        
    }else if (row == 1) {
        //修改密码
        ZPChangePwdViewController  *viewController = [[ZPChangePwdViewController alloc] init];
        viewController.flag = 101;
        [self.navigationController pushViewController:viewController animated:YES];
    }
}

#pragma mark - UIActionSheet Delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        NSInteger  tag = actionSheet.tag;
        if (tag == ClearCacheActionSheetTag) {
            [self  cleanCache];
        }else if (tag == LogOutActionSheetTag) {
            [self  doLogOutAction];
        }
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
